package com.hmdp.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hmdp.constant.GlobalConstant;
import com.hmdp.entity.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;
@Slf4j
public class MyLoginInterceptor implements HandlerInterceptor {
    private RedisTemplate redisTemplate;
    public MyLoginInterceptor(RedisTemplate redisTemplate)
    {
        this.redisTemplate=redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        log.info("token:"+token);
        if(StrUtil.isBlankIfStr(token))
        {
            log.info("token验证失败");
            response.setStatus(401);
            return false;
        }
        String s=(String) redisTemplate.opsForValue().get(GlobalConstant.TOKE_PREFIX + token);
        if(s==null)
        {
            log.info("token已失效");
            response.setStatus(401);
            return false;
        }
        JSONObject jsonObject = JSON.parseObject(s);
        User user = jsonObject.toJavaObject(User.class);
        if(user==null)
        {
            log.info("用户查找失败");
            response.setStatus(401);
            return false;
        }
        redisTemplate.expire(GlobalConstant.TOKE_PREFIX+token,GlobalConstant.TOKEN_TTL, TimeUnit.MINUTES);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        UserHolder.saveUser(userDTO);
        log.info("放行。。。");
        return true;
    }
}
